from django.views import View

from Venue.models import VenueSport
from sportsground.utils import Req
from sportsground.utils.Res import Res
from sportsground.utils.views import LoginRequired


class SportView(View):
    """ 场地运动类型信息 """

    def get(self, request):
        """ 查询 """
        # venue = request.user.venue
        # sports = venue.venuesport_set.all()
        sports = VenueSport.objects.all()
        result = []
        for sport in sports:
            result.append(sport.Info())
        return Res.Json(Res.OK, result=result)

    @LoginRequired.Venue
    @Req.getJson
    def post(self, request):
        """ 添加 """
        name = request.json_dict.get("name")

        venue = request.user.venue
        sport = VenueSport.create(name, venue)
        return Res.Json(Res.OK, result=sport.Info())

    @LoginRequired.Venue
    @Req.getJson
    def put(self, request):
        """ 修改 """
        id = request.json_dict.get("id")
        name = request.json_dict.get("name")

        venue = request.user.venue
        sport = VenueSport.objects.filter(id=id, venue=venue).first()
        if not sport:
            return Res.Json(Res.ParamErr)

        sport.name = name
        sport.save()
        return Res.Json(Res.OK)

    @LoginRequired.Venue
    @Req.getJson
    def delete(self, request):
        """ 删除 """
        id = request.json_dict.get("id")

        venue = request.user.venue
        sport = VenueSport.objects.filter(id=id, venue=venue).first()
        if not sport:
            return Res.Json(Res.ParamErr)

        sport.delete()
        return Res.Json(Res.OK)